const PahoMQTT = require('paho-mqtt');
import request from '@/utils/request';
const envConfig = require('@/config/env.config');

let client;
const listenCallback: any = {};
const MySocket: any = {};
const getMqttComm = ({ params, ...rest }) => {
  return request({
    url: '/api/restrict/matchscore',
    method: 'POST',
    ...params,
    ...rest,
  });
};
MySocket.mqttReconnect = (topic, client_id, callback) => {
  setTimeout(() => {
    MySocket.initMQTTReconnect(topic, client_id, callback);
  }, 150);
};
MySocket.initMQTTReconnect = (topic, client_id, callback) => {
  const reConnect = (op, username, password) => {
    // 连接成功订阅频道
    client.connect({
      timeout: 3,
      userName: username,
      password: password,
      useSSL: envConfig.CRRR_PORT,
      mqttVersion: 4,
      onSuccess: () => {
        console.log('WS连接成功');
        client.subscribe(topic);
      },
      onFailure: (message) => {
        console.log('WS连接失败', message);
      },
    });
    //接收消息
    client.onMessageArrived = (message) => {
      // console.log("收到消息:", message.destinationName);
      let data: any = {},
        action = message.destinationName;
      //频道 message.destinationName
      //消息内容 message.payloadString;
      if (
        'destinationName' in message &&
        'payloadString' in message &&
        JSON.parse(message.payloadString)
      ) {
        let content = JSON.parse(message.payloadString);
        let arr = action.split('/');
        // console.log("收到消息具体内容:", content);
        if (action.indexOf('gamedata/app') === 0) {
          if (arr.length > 2) {
            action = 'action_gamedata_app_against';
            data = {
              param: arr,
              content: content,
            };
          } else {
            action = 'action_' + arr.join('_');
            data.content = content;
          }
        }
      } else {
        data.content = message;
      }
      action in listenCallback && listenCallback[action](data, callback);
    };

    // 连接断开事件 - 走重连机制
    client.onConnectionLost = function (res) {
      setTimeout(() => {
        MySocket.initMQTTReconnect(topic, client_id, callback);
      }, 1500);
      console.log('连接断开:', res);
    };
  };
  if (!topic) {
    console.log('连接失败:参数缺失');
    return false;
  }
  let op: any = {};
  op.topic = topic;
  client_id && op.client_id == client_id;
  getMqttComm({
    params: { data: op },
    successFun: (res) => {
      client = new PahoMQTT.Client(
        envConfig.COMET_DOMAIN,
        envConfig.COMET_PORT,
        res.data.client_id
      );
      // 连接成功订阅频道
      reConnect(op, res.data.username, res.data.password);
    },
    errorFun: (res) => {
      console.log('连接失败:' + res.message);
    },
  });
};

// 断开连接
MySocket.unsubscribe = (client_id) => {
  client.unsubscribe(client_id);
};
listenCallback.action_gamedata_app = (data, callback) => {
  callback && callback(data);
};
listenCallback.action_gamedata_app_against = (data, callback) => {
  callback && callback(data);
};

export default MySocket;
